package cn.bytecollege.admin.controller;

import cn.bytecollege.admin.service.CategoryService;
import cn.bytecollege.common.constant.Resource;
import cn.bytecollege.common.entity.Category;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "CategoryAddController",value = "/admin/categoryAdd")
public class CategoryAddController extends HttpServlet {
    private CategoryService categoryService = null;
    public CategoryAddController(){
        categoryService = new CategoryService();
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher(Resource.PAGE_LOCATION+"/admin/categoryAdd.jsp")
                .forward(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String msg = null;
        String categoryName = request.getParameter("categoryName");

        Category category = new Category();
        category.setCategoryName(categoryName);
        Category tempCategory = categoryService.findCategoryByCategoryName(categoryName);
        //如果分类存在
        if(tempCategory != null){
            msg = "该分类已存在！";
            request.setAttribute("msg",msg);
            request.getRequestDispatcher(Resource.PAGE_LOCATION+"/admin/categoryAdd.jsp")
                    .forward(request,response);
            return;
        }
        msg = "添加成功！";
        request.setAttribute("msg",msg);
        categoryService.save(category);
        request.getRequestDispatcher(Resource.PAGE_LOCATION+"/admin/categoryAdd.jsp")
                .forward(request,response);
    }
}
